package com.ming.stringstudy.feedbacksystem.filter;

import com.alibaba.fastjson.JSONObject;
import com.ming.stringstudy.feedbacksystem.pojo.Result;
import com.ming.stringstudy.feedbacksystem.utils.HeaderName;
import com.ming.stringstudy.feedbacksystem.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;


        // 获取请求url
        String url = req.getRequestURI();

        // 判断请求url是否包含login，如果包含，说明是登录请求，直接放行
        if (url.contains("login")||url.contains("register")) {
            log.info("登录操作，放行");
            chain.doFilter(request, response);
            return;
        }

        String jwt = req.getHeader(HeaderName.headerName);

        // 判断jwt是否存在，如果不存在，返回错误结果
        if (!StringUtils.hasLength(jwt)){
            Result error = Result.error("not login");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        log.info("验证通过，放行");
        chain.doFilter(request, response);
    }
}
